﻿using NginxLogAnalyzer.Common;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace NginxLogAnalyzer
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            DataTable dataTable = new DataTable();
            var path = txtFilePath.Text;
            dataTable.Columns.Add("Month", typeof(string));
            dataTable.Columns.Add("Time", typeof(DateTime));
            dataTable.Columns.Add("Url", typeof(string));

            if (Directory.Exists(path))
            {
                ReadDirectory(path, ref dataTable);
            }
            else if (File.Exists(path))
            {
                ReadFile(path, ref dataTable);
            }

            //dataGrid.AutoGenerateColumns = true;
            //dataGrid.ItemsSource = dataTable.AsDataView();

            using (var con = new SqlConnection("Data Source=.;Initial Catalog=dmc;Persist Security Info=True;User ID=sa;Password=123456"))
            {
                con.Open();
                con.BulkCopy(dataTable, 1000000, "nginx_log");
                con.Close();
            }
        }

        private void ReadDirectory(string dir, ref DataTable dataTable)
        {
            var directorys = Directory.GetDirectories(dir);
            foreach (var d in directorys)
            {
                if (Directory.Exists(d))
                {
                    ReadDirectory(d, ref dataTable);
                }
            }

            var files = Directory.GetFiles(dir);
            foreach (var filePath in files)
            {
                if (File.Exists(filePath))
                {
                    ReadFile(filePath, ref dataTable);
                }
            }
        }

        private void ReadFile(string filePath, ref DataTable dataTable)
        {
            using (var file = File.Open(filePath, FileMode.Open, FileAccess.Read))
            using (var sr = new StreamReader(file))
            {
                var s = "";
                //int maxRow = 10;
                //while (maxRow > 0)
                //{
                //    s = sr.ReadLine();
                //    if (s.StartsWith("#Fields"))
                //    {
                //        var columns = s.Substring(s.IndexOf("#Fields: ") + "#Fields: ".Length).Split(' ');
                //        foreach (var item in columns)
                //        {
                //            if (!string.IsNullOrEmpty(item))
                //            {
                //                dataTable.Columns.Add(new DataColumn(item, typeof(string)));
                //            }
                //        }
                //        break;
                //    }
                //    maxRow--;
                //}

                while (!sr.EndOfStream)
                {
                    s = sr.ReadLine();
                    if (!s.StartsWith("#"))
                    {
                        var row = dataTable.NewRow();
                        //var cells = s.Split(' ');
                        var timeRegex = new Regex("\\[.*?\\]");
                        var urlRegex = new Regex("\".* HTTP/.*?\"");
                        //for (var i = 0; i < dataTable.Columns.Count; i++)
                        //{
                        //    row[i] = cells[i];
                        //}
                        //[17/Apr/2020:09:31:36 +0800]
                        var timeStr = timeRegex.Match(s).Value;
                        timeStr = timeStr.Substring(1, timeStr.Length - 2);
                        int pos = timeStr.IndexOf(':');
                        var time = DateTime.Parse(timeStr.Substring(0, pos) + " " + timeStr.Substring(pos + 1));
                        row[0] = time.ToString("yyyy-MM");
                        row[1] = time.ToString("yyyy-MM-dd hh:mm:ss");
                        row[2] = urlRegex.Match(s).Value;
                        dataTable.Rows.Add(row);
                    }
                }
            }
        }
    }
}
